package com.x.erp.util;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.x.erp.thirdparty.HomeCarInfo;
import com.x.framework.remote.HttpClient;

@Component
public class QczjApi {

	@Autowired
	private HttpClient httpClient;

	/**
	 * 添加车源信息
	 * @param dealerid 汽车之家商家ID
	 * @param key 汽车之家商家标识
	 * @param carInfo 车辆信息
	 * @return
	 * @throws Exception 
	 */
	public QczjResult insertCar(Integer dealerid, String key, HomeCarInfo carInfo) throws Exception{
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("_appid", Constant.QCZJ_APPID);
		paramMap.put("dealerid", dealerid);
		paramMap.put("key", key);
		paramMap.put("carinfo", JSON.toJSONString(carInfo));
		String result = httpClient.doPostMap(Constant.QCZJ_INSERT_CAR_URL, paramMap);
		return JSONObject.parseObject(result, QczjResult.class);
	}
	
	/**
	 * 上传图片
	 * @param dealerid 汽车之家商家ID
	 * @param key 汽车之家商家标识
	 * @param imgUrl 图片地址
	 * @param serialnum 图片顺序
	 * @return
	 */
	public QczjResult uploadImage(Integer dealerid, String key, String imgUrl, Integer serialnum) throws Exception{
		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("_appid", Constant.QCZJ_APPID);
		paramMap.put("dealerid", dealerid + "");
		paramMap.put("key", key);
		paramMap.put("serialnum", serialnum + "");
		Map<String, InputStream> fileMap = new HashMap<String, InputStream>();
		byte[] b = downloadImg(imgUrl);
		if(b != null){
			fileMap.put("imagefile", new ByteArrayInputStream(b));
		}
        String res = doPostUpload(Constant.QCZJ_UPLOAD_IMAGE_URL, paramMap, fileMap);
		return JSONObject.parseObject(res, QczjResult.class);
	}
	
	/**
	 * 获取销售代表
	 * @param dealerid 汽车之家商家ID
	 * @param key 汽车之家商家标识
	 * @return
	 */
	public QczjResult getSales(Integer dealerid, String key) throws Exception{
		String result = httpClient.doGet(Constant.QCZJ_GET_SALES_URL + "?_appid=" + Constant.QCZJ_APPID + "&dealerid=" + dealerid + "&key=" + "9Xm6KAPALGl2fPR%2bJaX0oOvdK2UmE%2b2sHZ43j6MhYFs5p0aTZUbPGTyU1Jo19O%2fwfoob3ZLI3bC20qJ8UFIpdQgA3b3TrOwi");
		return JSONObject.parseObject(result, QczjResult.class);
	}
	
	/**
	 * 车源设置为下架
	 * @param dealerid 汽车之家商家ID
	 * @param key 汽车之家商家标识
	 * @param carid 汽车之家车辆ID
	 * @return
	 */
	public QczjResult setCarInvalid(Integer dealerid, String key, Integer carid) throws Exception{
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("_appid", Constant.QCZJ_APPID);
		paramMap.put("dealerid", dealerid);
		paramMap.put("key", key);
		paramMap.put("carid", carid);
		String result = httpClient.doPostMap(Constant.QCZJ_SET_INVALID_URL, paramMap);
		return JSONObject.parseObject(result, QczjResult.class);
	}
	
	/**
	 * 车源设置为上架
	 * @param dealerid 汽车之家商家ID
	 * @param key 汽车之家商家标识
	 * @param carid 汽车之家车辆ID
	 * @return
	 */
	public QczjResult setCarRepublish(Integer dealerid, String key, Integer carid) throws Exception{
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("_appid", Constant.QCZJ_APPID);
		paramMap.put("dealerid", dealerid);
		paramMap.put("key", key);
		paramMap.put("carid", carid);
		String result = httpClient.doPostMap(Constant.QCZJ_REPUBLISH_CAR_URL, paramMap);
		return JSONObject.parseObject(result, QczjResult.class);
	}
	
	/**
	 * 车源设置为已售
	 * @param dealerid 汽车之家商家ID
	 * @param key 汽车之家商家标识
	 * @param carid 汽车之家车辆ID
	 * @param selledprice 汽车之家车辆售价
	 * @return
	 */
	public QczjResult setSaledCar(Integer dealerid, String key, Integer carid, BigDecimal selledprice) throws Exception{
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("_appid", Constant.QCZJ_APPID);
		paramMap.put("dealerid", dealerid);
		paramMap.put("key", key);
		paramMap.put("carid", carid);
		paramMap.put("selledprice", selledprice);
		String result = httpClient.doPostMap    (Constant.QCZJ_SET_SALED_URL, paramMap);
		return JSONObject.parseObject(result, QczjResult.class);
	}

	/**
	 * 获取颜色
	 * @return
	 */
	private Map<String, Integer> colorHash = new HashMap<String, Integer>();
	public QczjApi(){
		colorHash.put("黑色",1);
		colorHash.put("白色",2);
		colorHash.put("银色",3);
		colorHash.put("灰色",4);
		colorHash.put("红色",5);
		colorHash.put("蓝色",6);
		colorHash.put("绿色",7);
		colorHash.put("黄色",8);
		colorHash.put("香槟色",9);
		colorHash.put("紫色",10);
		colorHash.put("其他",11);
		colorHash.put("橙色",12);
		colorHash.put("棕色",13);
	}

	public Integer getColorId(String color) {
		return colorHash.get(color);
	}

	/**
	 * 获取图片文件流
	 * @param imgUrl 图片地址
	 * @return
	 */
	private byte[] downloadImg(String imgUrl) {
		try {
			// 构造URL
			URL url = new URL(imgUrl);
			// 打开连接
			URLConnection con = url.openConnection();
			// 设置请求超时时间
			con.setConnectTimeout(5 * 1000);
			// 输入流
			InputStream is = con.getInputStream();
			// 1K的数据缓冲
			byte[] bs = new byte[1024];
			// 读取到的数据长度
			int len;
			// 开始读取
			ByteArrayOutputStream os = new ByteArrayOutputStream();  
			while ((len = is.read(bs)) != -1) {
				os.write(bs, 0, len);
			}
			byte[] btImg = os.toByteArray();
			// 完毕，关闭所有链接
			os.close();
			is.close();
			return btImg;
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return null;
	}
	
	/** 
     * 上传图片工具
     * @param urlStr 
     * @param textMap 
     * @param fileMap 
     * @return 
     */  
    private String doPostUpload(String urlStr, Map<String, String> textMap, Map<String, InputStream> fileMap) {  
        String res = "";  
        HttpURLConnection conn = null;  
        String BOUNDARY = "---------------------------123821742118716"; //boundary就是request头和上传文件内容的分隔符    
        try {  
            URL url = new URL(urlStr);  
            conn = (HttpURLConnection) url.openConnection();  
            conn.setConnectTimeout(5000);  
            conn.setReadTimeout(30000);  
            conn.setDoOutput(true);  
            conn.setDoInput(true);  
            conn.setUseCaches(false);  
            conn.setRequestMethod("POST");  
            conn.setRequestProperty("Connection", "Keep-Alive");  
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);  
            OutputStream out = new DataOutputStream(conn.getOutputStream());  
            if (textMap != null) {  
                StringBuffer strBuf = new StringBuffer();  
                Iterator<Map.Entry<String, String>> iter = textMap.entrySet().iterator();  
                while (iter.hasNext()) {  
                    Map.Entry<String, String> entry = iter.next();  
                    String inputName = (String) entry.getKey();  
                    String inputValue = (String) entry.getValue();  
                    if (inputValue == null) {  
                        continue;  
                    }  
                    strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");  
                    strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"\r\n\r\n");  
                    strBuf.append(inputValue);  
                }  
                out.write(strBuf.toString().getBytes());  
            }  
  
            // file    
            if (fileMap != null) {  
                Iterator<Map.Entry<String, InputStream>> iter = fileMap.entrySet().iterator();  
                while (iter.hasNext()) {  
                    Map.Entry<String, InputStream> entry = iter.next();  
                    String inputName = entry.getKey();  
                    InputStream inputValue = entry.getValue();  
                    if (inputValue == null) {  
                        continue;  
                    }  
                    StringBuffer strBuf = new StringBuffer();  
                    strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");  
                    strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"xx.jpg\"\r\n");  
                    strBuf.append("Content-Type:image/jpeg\r\n\r\n");  
  
                    out.write(strBuf.toString().getBytes());  
  
                    DataInputStream in = new DataInputStream(inputValue);  
                    int bytes = 0;  
                    byte[] bufferOut = new byte[1024];  
                    while ((bytes = in.read(bufferOut)) != -1) {  
                        out.write(bufferOut, 0, bytes);  
                    }  
                    in.close();  
                }  
            }  
  
            byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();  
            out.write(endData);  
            out.flush();  
            out.close();  
            // 读取返回数据    
            StringBuffer strBuf = new StringBuffer();  
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));  
            String line = null;  
            while ((line = reader.readLine()) != null) {  
                strBuf.append(line).append("\n");  
            }  
            res = strBuf.toString();  
            reader.close();  
            reader = null;  
        } catch (Exception e) {  
            System.out.println("发送POST请求出错。" + urlStr);  
            e.printStackTrace();  
        } finally {  
            if (conn != null) {  
                conn.disconnect();  
                conn = null;  
            }  
        }  
        return res;  
    }
	
}
